<template>
    <div class="dicom-container">
        <!-- 工具栏 -->
        <div class="toolbar">
            <!-- General Tools (通用工具) -->
            <!-- <button @click="setTool('DoubleTapFitToWindow')">适应窗口</button> -->
            <button @click="setTool('DragProbe')">拖动探针</button>
            <button @click="setTool('Eraser')">擦除</button>
            <button @click="setTool('Magnify')">放大镜</button>
            <!-- <button @click="setTool('OrientationMarkers')">方向标记</button>
            <button @click="setTool('PanMultiTouch')">多点触控平移</button> -->
            <button @click="flipHorizontal()">水平镜像</button>
            <button @click="flipVertical()">垂直镜像</button>
            <button @click="rotateClockwise('clockwise')">顺时针旋转90</button>
            <button @click="rotateClockwise('anticlockwise')">逆时针旋转90</button>
            <button @click="toggleReliefEffect()">浮雕效果</button>
            <button @click="toggleImageMode()">正负片</button>
            <button @click="zoomIn()">放大</button>
            <button @click="zoomOut()">缩小</button>

            <button @click="setTool('Pan')">平移</button>
            <!-- <button @click="setTool('rotateMultiTouch')">多点触控旋转</button> -->
            <button @click="setTool('Rotate')">旋转</button>
            <button @click="setTool('ScaleOverlay')">比例尺</button>
            <!-- <button @click="setTool('WWWCRegionTool')">窗中心调整</button> -->
            <button @click="setTool('ZoomMouseWheel')">鼠标滚轮缩放</button>
            <!-- <button @click="setTool('zoomTouchPinch')">捏合缩放</button> -->
            <button @click="setTool('Zoom')">点击缩放</button>
            <!-- <button @click="setTool('WWWC')">
                <i class="fas fa-sliders-h"></i> 窗宽窗位
            </button> -->
            <button @click="probeOpticalDensity('Zoom')">吸管</button>
            <!-- 标注工具 -->
            <button @click="setTool('Angle')">角度</button>
            <button @click="setTool('ArrowAnnotate')">箭头标注</button>
            <button @click="setTool('Bidirectional')">双向测量</button>
            <button @click="setTool('CobbAngle')">Cobb角度测量</button>
            <button @click="setTool('EllipticalRoi')">椭圆形</button>
            <button @click="setTool('FreehandRoi')">手绘</button>
            <button @click="setTool('Length')">长度测量</button>
            <button @click="setTool('Probe')">探针</button>
            <button @click="setTool('RectangleRoi')">矩形</button>

            <button @click="clearAllMeasurements">清除所有标注</button>
            <button @click="resetViewport">重置视图</button>
            <input type="file" @change="loadDicomFile" accept=".dcm" ref="fileInput">
        </div>

        <!-- 视图区域 -->
        <div ref="viewport" class="viewport"
            :class="[reliefEffectEnabled ? 'relief-effect' : '', invertEffectEnabled ? 'invert-effect' : '']">
            <div class="pixel-info-display">
                <div class="pixel-info-header">
                    <i class="fas fa-eye-dropper"></i>
                    <span>像素值与黑度值测量</span>
                </div>
                <div class="pixel-info-row">
                    <span class="pixel-info-label">当前位置:</span>
                    <span class="pixel-info-value">256, 256</span>
                </div>
                <div class="pixel-info-row">
                    <span class="pixel-info-label">像素值:</span>
                    <span class="pixel-info-value">186</span>
                </div>
                <div class="pixel-info-row">
                    <span class="pixel-info-label">黑度值 (OD):</span>
                    <span class="pixel-info-value">0.73</span>
                </div>
                <div class="pixel-info-row">
                    <span class="pixel-info-label">灰度等级:</span>
                    <span class="pixel-info-value">中等</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import dicomParser from 'dicom-parser';
import cornerstone from 'cornerstone-core';
import cornerstoneMath from 'cornerstone-math';
import cornerstoneTools from 'cornerstone-tools';
import Hammer from 'hammerjs';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'
import { configureCornerstone } from '@/utils/cornerstoneConfig';

export default {
    name: 'DicomViewer',
    data() {
        return {
            currentImageId: null,
            element: null,
            dicomFiles: [],
            activeTool: null,
            isFlipped: false,//水平镜像
            isFlippedVertical: false,//垂直镜像
            currentRotation: 0,//旋转度数
            reliefEffectEnabled: false,//浮雕效果
            invertEffectEnabled: false,//正负片
            currentZoom: 1,//缩放
            pixelValues: [],
            pixelMarkers: [],
            currentPixel: { x: 0, y: 0, value: 0, huValue: 0 },
            currentImage: null,
            tools: {
                // 通用工具
                // doubleTapFitToWindow: 'DoubleTapFitToWindow',//双击图像使其适应窗口大小
                dragProbe: 'DragProbe',//拖动探针工具，用于测量像素值
                eraser: 'Eraser ',//擦除工具，用于清除标注
                magnify: 'Magnify',//放大镜工具，放大查看图像局部区域
                // orientationMarkers: 'OrientationMarkers',//方向标记工具，显示图像方向
                // panMultiTouch: 'PanMultiTouch',//多点触控平移工具
                pan: 'Pan',//平移工具，移动图像
                // rotateMultiTouch: 'RotateMultiTouch',//多点触控旋转工具
                rotate: 'Rotate',//旋转工具，旋转图像
                scaleOverlay: 'ScaleOverlay',//比例尺覆盖工具，显示比例尺
                // wWWCRegion: 'WWWCRegion',//窗宽窗中心区域调整工具
                wWWC: 'WWWC',//窗宽窗中心调整工具
                zoomMouseWheel: 'ZoomMouseWheel',//鼠标滚轮缩放工具
                // zoomTouchPinch: 'ZoomTouchPinch',//捏合缩放工具
                zoom: 'Zoom',//缩放工具
                // 标注工具
                angle: 'Angle',//角度测量工具，测量两点间的角度
                arrowAnnotate: 'ArrowAnnotate', //箭头标注工具，添加带箭头的文本标注
                bidirectional: 'Bidirectional', //双向测量工具，测量两个方向的尺寸
                cobbAngle: 'CobbAngle', //Cobb角度测量工具，用于脊柱侧弯测量
                ellipticalRoi: 'EllipticalRoi', //椭圆形ROI(感兴趣区域)工具
                freehandRoi: 'FreehandRoi',//手绘ROI工具
                length: 'Length',//长度测量工具
                probe: 'Probe',//探针工具，查看特定位置的像素值
                rectangleRoi: 'RectangleRoi',//矩形
            }
        };
    },
    mounted() {
        this.initViewer();
    },
    beforeDestroy() {
        this.disableViewer();
    },
    methods: {
        initViewer() {
            // 初始化元素
            this.element = this.$refs.viewport;
            cornerstone.enable(this.element);
            // 配置图像加载器
            cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
            cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
            cornerstoneWADOImageLoader.webWorkerManager.initialize();
            cornerstoneWADOImageLoader.configure();

            // 必须先配置外部依赖
            cornerstoneTools.external.cornerstone = cornerstone;
            cornerstoneTools.external.Hammer = Hammer;
            cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
            cornerstoneTools.external.dicomParser = dicomParser;
            // 初始化工具系统
            cornerstoneTools.init({
                globalToolSyncEnabled: true,
                showSVGCursors: true,
                touchEnabled: true, // 启用触摸支持
                mouseEnabled: true // 确保鼠标事件启用
            });
            // 配置工具样式
            cornerstoneTools.toolStyle.setToolWidth(2);
            cornerstoneTools.toolColors.setToolColor('rgb(255, 255, 0)');
            cornerstoneTools.toolColors.setActiveColor('rgb(0, 255, 0)');
            // 添加工具
            this.addTools();
        },

        // 添加工具
        addTools() {
            // 清除可能存在的旧工具
            // cornerstoneTools.addTool(cornerstoneTools.DoubleTapFitToWindowTool);
            cornerstoneTools.removeTool(cornerstoneTools.DragProbeTool);
            cornerstoneTools.removeTool(cornerstoneTools.EraserTool);
            cornerstoneTools.removeTool(cornerstoneTools.MagnifyTool);
            // cornerstoneTools.removeTool(cornerstoneTools.OrientationMarkersTool);
            // cornerstoneTools.removeTool(cornerstoneTools.PanMultiTouchTool);
            cornerstoneTools.removeTool(cornerstoneTools.PanTool);
            // cornerstoneTools.removeTool(cornerstoneTools.RotateMultiTouchTool);
            cornerstoneTools.removeTool(cornerstoneTools.RotateTool);
            cornerstoneTools.removeTool(cornerstoneTools.ScaleOverlayTool);

            // cornerstoneTools.removeTool(cornerstoneTools.WWWCRegionTool);
            // cornerstoneTools.removeTool(cornerstoneTools.WWWCTool);
            cornerstoneTools.removeTool(cornerstoneTools.ZoomMouseWheelTool);
            // cornerstoneTools.removeTool(cornerstoneTools.ZoomTouchPinchTool);
            cornerstoneTools.removeTool(cornerstoneTools.ZoomTool);
            // 标注工具
            cornerstoneTools.removeTool(cornerstoneTools.AngleTool);
            cornerstoneTools.removeTool(cornerstoneTools.ArrowAnnotateTool);
            cornerstoneTools.removeTool(cornerstoneTools.BidirectionalTool);
            cornerstoneTools.removeTool(cornerstoneTools.CobbAngleTool);
            cornerstoneTools.removeTool(cornerstoneTools.EllipticalRoiTool);
            cornerstoneTools.removeTool(cornerstoneTools.FreehandRoiTool);
            cornerstoneTools.removeTool(cornerstoneTools.LengthTool);
            cornerstoneTools.removeTool(cornerstoneTools.ProbeTool);
            cornerstoneTools.removeTool(cornerstoneTools.RectangleRoiTool);

            // 注册工具
            // 通用工具
            // cornerstoneTools.addTool(cornerstoneTools.DoubleTapFitToWindowTool);
            cornerstoneTools.addTool(cornerstoneTools.DragProbeTool);
            cornerstoneTools.addTool(cornerstoneTools.EraserTool);
            cornerstoneTools.addTool(cornerstoneTools.MagnifyTool);
            // cornerstoneTools.addTool(cornerstoneTools.OrientationMarkersTool);
            // cornerstoneTools.addTool(cornerstoneTools.PanMultiTouchTool);
            cornerstoneTools.addTool(cornerstoneTools.PanTool);
            // cornerstoneTools.addTool(cornerstoneTools.RotateMultiTouchTool);
            cornerstoneTools.addTool(cornerstoneTools.RotateTool);
            cornerstoneTools.addTool(cornerstoneTools.ScaleOverlayTool);
            // cornerstoneTools.addTool(cornerstoneTools.WWWCRegionTool);
            // cornerstoneTools.addTool(cornerstoneTools.WWWCTool);
            cornerstoneTools.addTool(cornerstoneTools.ZoomMouseWheelTool);
            // cornerstoneTools.addTool(cornerstoneTools.ZoomTouchPinchTool);
            cornerstoneTools.addTool(cornerstoneTools.ZoomTool);
            // 标注工具
            cornerstoneTools.addTool(cornerstoneTools.AngleTool);
            cornerstoneTools.addTool(cornerstoneTools.ArrowAnnotateTool);
            cornerstoneTools.addTool(cornerstoneTools.BidirectionalTool);
            cornerstoneTools.addTool(cornerstoneTools.CobbAngleTool);
            cornerstoneTools.addTool(cornerstoneTools.EllipticalRoiTool);
            cornerstoneTools.addTool(cornerstoneTools.FreehandRoiTool);
            cornerstoneTools.addTool(cornerstoneTools.LengthTool);
            cornerstoneTools.addTool(cornerstoneTools.ProbeTool);
            cornerstoneTools.addTool(cornerstoneTools.RectangleRoiTool);

        },
        // 加载dicm文件
        async loadDicomFile(event) {
            const file = event.target.files[0];
            if (!file) return;

            try {
                // 生成图像ID
                const imageId = cornerstoneWADOImageLoader.wadouri.fileManager.add(file);
                this.currentImageId = imageId;
                // 加载并显示图像
                const image = await cornerstone.loadImage(imageId);
                cornerstone.displayImage(this.element, image);
                this.currentImage = image; // 存储当前图像
                // 图像加载后重新激活当前工具
                if (this.activeTool) {
                    this.setTool(this.activeTool);
                }

            } catch (error) {
                console.error('加载失败:', error);
                this.$emit('error', 'DICOM文件加载失败: ' + error.message);
            }
        },

        setTool(toolName) {
            this.activeTool = toolName;
            // 停用非toolName所有工具
            this.deactivateOtherTools(toolName);
            // 激活选定工具
            cornerstoneTools.setToolActive(toolName, { mouseButtonMask: 1 });
            // 切换工具时清除像素标记
            if (toolName !== 'Probe') {
                this.pixelMarkers = [];
            }
        },
        //  停用非toolName所有工具
        deactivateOtherTools(activeTool) {
            Object.values(this.tools).forEach(tool => {
                if (tool !== activeTool) {
                    cornerstoneTools.setToolDisabled(tool);
                }
            });
        },
        // 水平镜像
        flipHorizontal() {
            if (!this.element) return;
            this.isFlipped = !this.isFlipped;
            const viewport = cornerstone.getViewport(this.element);
            // 应用水平翻转
            if (!viewport) return;
            viewport.hflip = this.isFlipped;
            cornerstone.setViewport(this.element, viewport);
        },
        // 垂直镜像功能
        flipVertical() {
            if (!this.element) return;
            this.isFlippedVertical = !this.isFlippedVertical;
            const viewport = cornerstone.getViewport(this.element);
            // 应用水平翻转
            if (!viewport) return;
            viewport.vflip = this.isFlippedVertical;
            cornerstone.setViewport(this.element, viewport);
        },
        // 顺时针/逆时针 旋转90度功能
        rotateClockwise(type) {
            if (!this.element) return;
            // 增加90度旋转
            this.currentRotation = (this.currentRotation + 90) % 360;
            if (type === 'anticlockwise') {
                this.currentRotation = -(this.currentRotation + 90) % 360;
            }
            const viewport = cornerstone.getViewport(this.element);
            // 应用水平翻转
            if (!viewport) return;
            viewport.rotation = this.currentRotation;
            cornerstone.setViewport(this.element, viewport);

        },
        // 浮雕效果功能
        toggleReliefEffect() {
            this.reliefEffectEnabled = !this.reliefEffectEnabled;
        },
        // 设置图像模式
        toggleImageMode() {
            this.invertEffectEnabled = !this.invertEffectEnabled;
        },
        // 缩放功能
        zoomIn() {
            if (this.currentZoom >= 3) return;
            this.currentZoom += 0.1;
            console.log(this.currentZoom, 'this.currentZoom')
            this.applyZoom();
            // viewport.classList.add('zooming-in');
            // setTimeout(() => {
            //     viewport.classList.remove('zooming-in');
            // }, 300);
            // showStatusMessage(`放大至 ${Math.round(currentZoom * 100)}%`, 1500);
        },

        zoomOut() {
            if (this.currentZoom <= 0.2) return;
            this.currentZoom -= 0.1;
            this.applyZoom();
        },
        applyZoom() {
            if (!this.element) return;
            const viewport = cornerstone.getViewport(this.element);
            // 应用水平翻转
            if (!viewport) return;
            viewport.scale = this.currentZoom;
            cornerstone.setViewport(this.element, viewport);
        },
        handleMouseMove(event) {
            if (!this.currentImage || this.activeTool !== 'Probe') return;

            const rect = this.element.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            // 获取像素值
            this.getPixelValue(x, y);
        },

        handlePixelClick(event) {
            if (!this.currentImage || this.activeTool !== 'Probe') return;

            const rect = this.element.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            // 获取像素值
            const pixel = this.getPixelValue(x, y);

            // 添加标记
            if (pixel) {
                this.pixelMarkers.push({
                    x: x,
                    y: y,
                    value: pixel.value,
                    huValue: pixel.huValue
                });

                this.pixelValues.push(pixel);
            }
        },

        getPixelValue(x, y) {
            if (!this.currentImage) return null;

            try {
                // 将页面坐标转换为像素坐标
                const pixelCoords = cornerstone.pageToPixel(this.element, x, y);

                // 获取图像尺寸
                const width = this.currentImage.columns || 512;
                const height = this.currentImage.rows || 512;

                // 检查坐标是否在图像范围内
                if (pixelCoords.x < 0 || pixelCoords.x >= width ||
                    pixelCoords.y < 0 || pixelCoords.y >= height) {
                    return null;
                }

                // 获取像素数据
                const pixelData = this.currentImage.getPixelData();
                if (!pixelData) return null;

                // 计算像素索引
                const index = Math.floor(pixelCoords.y) * width + Math.floor(pixelCoords.x);
                const pixelValue = pixelData[index];

                // 计算HU值
                const huValue = Math.round(pixelValue * this.currentImage.slope + this.currentImage.intercept);

                // 更新当前像素
                this.currentPixel = {
                    x: Math.floor(pixelCoords.x),
                    y: Math.floor(pixelCoords.y),
                    value: pixelValue,
                    huValue: huValue
                };

                return this.currentPixel;
            } catch (error) {
                console.error('获取像素值时出错:', error);
                return null;
            }
        },
        probeOpticalDensity() {
            const viewport = this.element;
            // 模拟吸管功能
            viewport.addEventListener('click', (e) => {
                const rect = viewport.getBoundingClientRect();
                const x = e.clientX - rect.left;
                const y = e.clientY - rect.top;

                // 在实际应用中，这里会获取真实的像素值
                // 这里我们模拟一个像素值
                const pixelValue = Math.floor(Math.random() * 256);

                // 计算黑度值 (Optical Density)
                const opticalDensity = calculateOpticalDensity(pixelValue);
                console.log(opticalDensity.toFixed(2), 'opticalDensity.toFixed(2)')
                return;
                // 更新显示
                // document.querySelectorAll('.pixel-info-value')[0].textContent = `${Math.floor(x)}, ${Math.floor(y)}`;
                // document.querySelectorAll('.pixel-info-value')[1].textContent = pixelValue;
                // document.querySelectorAll('.pixel-info-value')[2].textContent = opticalDensity.toFixed(2);
                // let densitySlider = document.querySelector('.density-value');
                // // 更新密度显示
                // densitySlider.textContent = opticalDensity.toFixed(2);
                // const densityLevel = document.querySelector('.density-level');
                // // 更新密度条
                // const dmax = parseFloat(densitySlider.value);
                // const densityPercent = Math.min(100, (opticalDensity / dmax) * 100);
                // densityLevel.style.width = `${densityPercent}%`;

                // // 更新密度等级
                // let densityLevelText = '';
                // if (opticalDensity < 0.3) {
                //     densityLevelText = '低';
                // } else if (opticalDensity < 1.0) {
                //     densityLevelText = '中等';
                // } else if (opticalDensity < 2.0) {
                //     densityLevelText = '高';
                // } else {
                //     densityLevelText = '极高';
                // }
                // document.querySelectorAll('.pixel-info-value')[3].textContent = densityLevelText;
                // document.querySelectorAll('.density-value')[1].textContent = densityLevelText;

                // // 计算透射率
                // const transmission = Math.pow(10, -opticalDensity) * 100;
                // document.querySelectorAll('.density-value')[2].textContent = transmission.toFixed(1) + '%';

                // // 添加标记
                // const marker = document.querySelector('.pixel-marker');
                // const tag = document.querySelector('.pixel-value-tag');

                // marker.style.left = `${x}px`;
                // marker.style.top = `${y}px`;
                // tag.style.left = `${x}px`;
                // tag.style.top = `${y}px`;
                // tag.textContent = `${pixelValue} (OD: ${opticalDensity.toFixed(2)})`;
            });

            // 计算黑度值
            function calculateOpticalDensity(pixelValue) {
                // 归一化像素值 (0-255 到 0-1)
                const normalized = pixelValue / 255;

                // 光学密度公式: OD = -log10(I/I0)
                // 其中 I/I0 是透射率 (0-1)
                // 避免log(0)的情况
                const transmission = Math.max(0.01, normalized);
                return -Math.log10(transmission);
            }

        },
        // 清除所有标注
        clearAllMeasurements() {
            const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager;
            toolStateManager.restoreToolState({});
            cornerstone.updateImage(this.element);
            this.pixelMarkers = [];
            this.pixelValues = [];
        },
        resetViewport() {
            if (this.element && this.currentImageId) {
                this.currentZoom = 1;
                this.isFlipped = false;//水平镜像
                this.isFlippedVertical = false;//垂直镜像
                this.currentRotation = 0;//旋转度数
                this.reliefEffectEnabled = false;//浮雕效果
                this.invertEffectEnabled = false;//正负片
                cornerstone.reset(this.element);
                cornerstone.updateImage(this.element);
            }
        },

        disableViewer() {
            if (this.element) {
                cornerstone.disable(this.element);
            }
        }
    }
};
</script>

<style scoped>
.dicom-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.toolbar {
    padding: 10px;
    background: #f0f0f0;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.toolbar button {
    padding: 5px 10px;
    cursor: pointer;
}

.viewport {
    width: 100%;
    height: calc(100vh - 50px);
    background-color: #000;
    position: relative;
}

/* 浮雕 */
.relief-effect {
    animation: reliefAnimation 0.5s forwards;
    filter: grayscale(1) contrast(1.8) brightness(1.1);
}

@keyframes reliefAnimation {
    0% {
        filter: grayscale(1);
    }

    50% {
        filter: grayscale(1) contrast(1.5) brightness(1.2);
    }

    100% {
        filter: grayscale(1) contrast(1.8) brightness(1.1);
    }
}

/* 正负片 */
.invert-effect {
    filter: invert(100%);
}

.invert-effect.relief-effect {
    filter: invert(100%) grayscale(1) contrast(1.8) brightness(1.1);
}

/* 缩放动画 */
@keyframes zoomIn {
    from {
        transform: scale(1);
    }

    to {
        transform: scale(1.5);
    }
}

@keyframes zoomOut {
    from {
        transform: scale(1.5);
    }

    to {
        transform: scale(1);
    }
}

.zooming-in {
    animation: zoomIn 0.3s forwards;
}

.zooming-out {
    animation: zoomOut 0.3s forwards;
}

.pixel-info-display {
    position: absolute;
    top: 20px;
    right: 20px;
    background: rgba(0, 0, 0, 0.7);
    color: #00ff9d;
    padding: 10px 15px;
    border-radius: 10px;
    font-size: 0.9rem;
    z-index: 100;
    min-width: 180px;
    box-shadow: 0 0 15px rgba(0, 255, 157, 0.3);
    border: 1px solid #00ff9d;
}

.pixel-marker {
    position: absolute;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background: rgba(255, 0, 0, 0.5);
    border: 2px solid #ff0000;
    z-index: 99;
    pointer-events: none;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 10px rgba(255, 0, 0, 0.7);
}

.pixel-value-tag {
    position: absolute;
    background: rgba(0, 0, 0, 0.7);
    color: #00ff9d;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 101;
    pointer-events: none;
    transform: translate(-50%, -100%);
    white-space: nowrap;
    border: 1px solid #00ff9d;
}
</style>